package com.crazy.spring;


import com.crazy.spring.annotation.Autowired;
import com.crazy.spring.annotation.Component;
import com.crazy.spring.annotation.ComponentScan;
import com.crazy.spring.annotation.Scope;
import com.crazy.spring.aware.BeanNameAware;

import java.beans.Introspector;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Zhu Dunfeng
 * @date 2022/4/21 21:57
 */
public class AdunApplicationContext {

    private Class configClass;

    private ConcurrentHashMap<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>();

    /**
     * 一级缓存
     */
    private ConcurrentHashMap<String, Object> singletonObjects = new ConcurrentHashMap<>();

    private List<BeanPostProcessor> beanPostProcessorList = new ArrayList<>();

    public AdunApplicationContext(Class configClass) {
        this.configClass = configClass;

        //扫描---BeanDefinition---->BeanDefinitionMap
        if (this.configClass.isAnnotationPresent(ComponentScan.class)) {
            ComponentScan componentScanAnnotation = (ComponentScan) configClass.getAnnotation(ComponentScan.class);
            //扫描路径 com.adun.service
            String path = componentScanAnnotation.value();
            //替换成路径格式 com/adun/service
            path = path.replace(".", "/");

            ClassLoader classLoader = AdunApplicationContext.class.getClassLoader();
            //file:/D:/IdeaProjects/adun-spring/out/production/adun-spring/com/adun/service
            URL resource = classLoader.getResource(path);

            ///D:/IdeaProjects/adun-spring/out/production/adun-spring/com/adun/service
            String filePath = resource.getFile();
            File file = new File(filePath);

            //获取扫描的文件夹
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                for (File f : files) {
                    String fileName = f.getAbsolutePath();
                    //过滤.class
                    if (fileName.endsWith(".class")) {
                        //截取,获取加载类的全类名
                        String className = fileName.substring((classLoader.getResource("").getPath()).lastIndexOf("/"), fileName.indexOf(".class"));
                        className = className.replace("\\", ".");

                        try {
                            Class<?> clazz = classLoader.loadClass(className);
                            if (clazz.isAnnotationPresent(Component.class)) {
                                //获取自定义BeanPostProcessor
                                if (BeanPostProcessor.class.isAssignableFrom(clazz)) {
                                    BeanPostProcessor instance = (BeanPostProcessor) clazz.newInstance();
                                    beanPostProcessorList.add(instance);
                                }

                                //获取beanName
                                Component component = clazz.getAnnotation(Component.class);
                                String beanName = component.value();
                                if (null == beanName || "".equals(beanName)) {
                                    //默认的beanName
                                    beanName = Introspector.decapitalize(clazz.getSimpleName());
                                }

                                //BeanDefinition
                                BeanDefinition beanDefinition = new BeanDefinition();
                                beanDefinition.setType(clazz);
                                if (clazz.isAnnotationPresent(Scope.class)) {
                                    Scope scopeAnnotation = clazz.getAnnotation(Scope.class);
                                    beanDefinition.setScope(scopeAnnotation.value());
                                } else {
                                    beanDefinition.setScope("singletion");
                                }
                                beanDefinitionMap.put(beanName, beanDefinition);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

            }
        }

        //实例化单例bean
        for (String beanName : beanDefinitionMap.keySet()) {
            BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
            if ("singletion".equals(beanDefinition.getScope())) {
                Object bean = createBean(beanName, beanDefinition);
                singletonObjects.put(beanName, bean);
            }
        }
    }

    private Object createBean(String beanName, BeanDefinition beanDefinition) {
        Class clazz = beanDefinition.getType();
        try {
            Object instance = clazz.getConstructor().newInstance();
            //依赖注入
            for (Field f : clazz.getDeclaredFields()) {
                if (f.isAnnotationPresent(Autowired.class)) {
                    f.setAccessible(true);
                    f.set(instance, getBean(f.getName()));
                }
            }

            //Aware回调
            if (instance instanceof BeanNameAware) {
                ((BeanNameAware) instance).setBeanName(beanName);
            }

            //BeanPostProcesser 初始化 AOP
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                instance = beanPostProcessor.postProcessBeforeInitialization(beanName, instance);
            }

            //初始化
            if (instance instanceof InitializingBean) {
                ((InitializingBean) instance).afterPropertiesSet();
            }

            //BeanPostProcesser 初始化 AOP
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                instance = beanPostProcessor.postProcessAfterInitialization(beanName, instance);
            }
            //使用Processor实现AOP
            DefaultBeanProcessor defaultBeanProcessor = new DefaultBeanProcessor();
            instance = defaultBeanProcessor.postProcessAfterInitialization(beanName, instance);

            return instance;
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

        return null;
    }

//    private String lowerFirstCase(String str) {
//        char[] chars = str.toCharArray();
//        chars[0] += 32;
//        return String.valueOf(chars);
//    }

    public Object getBean(String beanName) {
        BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
        if (beanDefinition == null) {
            throw new NullPointerException();
        } else {
            String scope = beanDefinition.getScope();
            if ("singletion".equals(scope)) {
                //单例
                Object bean = singletonObjects.get(beanName);
                if (bean == null) {
                    bean = createBean(beanName, beanDefinition);
                    singletonObjects.put(beanName, bean);
                }
                return bean;
            } else {
                //多例
                return createBean(beanName, beanDefinition);
            }

        }
    }
}
